package com.xc.exception;

import com.xc.utils.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 自定义异常
     */
    @ExceptionHandler(BaseException.class)
    public <T> ResultVO<T> BaseExceptionHandler(BaseException ex) {
        printException(ex);
        return ResultVO.error(ex.getErrCode(), (T) ex.getMessage());
    }

    private void printException(Exception ex) {
        log.info("异常信息开始执行：👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇👇⬇");
        log.error("异常信息:", ex);
        log.info("异常信息结束执行。👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆👆⬆");
    }

    /**
     * 参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public <T> ResultVO<T> handleValidationExceptions(MethodArgumentNotValidException ex) {
        printException(ex);
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return ResultVO.error(400, (T) errors);
    }
}
